import { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit';
import { Product, ProductCategory, PaginatedResponse } from '../../types';
import { productAPI } from '../../services/api';

interface ProductState {
  categories: ProductCategory[];
  products: Product[];
  currentProduct: Product | null;
  recommendations: Product[];
  searchResults: Product[];
  pagination: {
    current: number;
    pageSize: number;
    total: number;
  };
  filters: {
    category?: number;
    search?: string;
    risk_level?: number;
  };
  loading: boolean;
  error: string | null;
}

const initialState: ProductState = {
  categories: [],
  products: [],
  currentProduct: null,
  recommendations: [],
  searchResults: [],
  pagination: {
    current: 1,
    pageSize: 20,
    total: 0,
  },
  filters: {},
  loading: false,
  error: null,
};

// 异步actions
export const fetchCategories = createAsyncThunk(
  'product/fetchCategories',
  async (_, { rejectWithValue }) => {
    try {
      const categories = await productAPI.getCategories();
      return categories;
    } catch (error: any) {
      return rejectWithValue(error.response?.data?.message || '获取产品分类失败');
    }
  }
);

export const fetchProducts = createAsyncThunk(
  'product/fetchProducts',
  async (params: {
    category?: number;
    search?: string;
    risk_level?: number;
    page?: number;
    page_size?: number;
  } = {}, { rejectWithValue }) => {
    try {
      const response = await productAPI.getProducts(params);
      return response;
    } catch (error: any) {
      return rejectWithValue(error.response?.data?.message || '获取产品列表失败');
    }
  }
);

export const fetchProduct = createAsyncThunk(
  'product/fetchProduct',
  async (id: number, { rejectWithValue }) => {
    try {
      const product = await productAPI.getProduct(id);
      return product;
    } catch (error: any) {
      return rejectWithValue(error.response?.data?.message || '获取产品详情失败');
    }
  }
);

export const searchProducts = createAsyncThunk(
  'product/searchProducts',
  async (keyword: string, { rejectWithValue }) => {
    try {
      const products = await productAPI.searchProducts(keyword);
      return products;
    } catch (error: any) {
      return rejectWithValue(error.response?.data?.message || '搜索产品失败');
    }
  }
);

export const fetchRecommendations = createAsyncThunk(
  'product/fetchRecommendations',
  async (risk_level: number, { rejectWithValue }) => {
    try {
      const products = await productAPI.getRecommendations(risk_level);
      return products;
    } catch (error: any) {
      return rejectWithValue(error.response?.data?.message || '获取产品推荐失败');
    }
  }
);

const productSlice = createSlice({
  name: 'product',
  initialState,
  reducers: {
    clearError: (state) => {
      state.error = null;
    },
    setFilters: (state, action: PayloadAction<{
      category?: number;
      search?: string;
      risk_level?: number;
    }>) => {
      state.filters = { ...state.filters, ...action.payload };
    },
    clearFilters: (state) => {
      state.filters = {};
    },
    setPagination: (state, action: PayloadAction<{
      current?: number;
      pageSize?: number;
    }>) => {
      state.pagination = { ...state.pagination, ...action.payload };
    },
    clearSearchResults: (state) => {
      state.searchResults = [];
    },
    clearRecommendations: (state) => {
      state.recommendations = [];
    },
    setCurrentProduct: (state, action: PayloadAction<Product | null>) => {
      state.currentProduct = action.payload;
    },
  },
  extraReducers: (builder) => {
    // 获取产品分类
    builder
      .addCase(fetchCategories.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(fetchCategories.fulfilled, (state, action: PayloadAction<ProductCategory[]>) => {
        state.loading = false;
        state.categories = action.payload;
        state.error = null;
      })
      .addCase(fetchCategories.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string;
      });

    // 获取产品列表
    builder
      .addCase(fetchProducts.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(fetchProducts.fulfilled, (state, action: PayloadAction<PaginatedResponse<Product>>) => {
        state.loading = false;
        state.products = action.payload.results;
        state.pagination = {
          ...state.pagination,
          total: action.payload.total_count,
        };
        state.error = null;
      })
      .addCase(fetchProducts.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string;
      });

    // 获取产品详情
    builder
      .addCase(fetchProduct.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(fetchProduct.fulfilled, (state, action: PayloadAction<Product>) => {
        state.loading = false;
        state.currentProduct = action.payload;
        state.error = null;
      })
      .addCase(fetchProduct.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string;
      });

    // 搜索产品
    builder
      .addCase(searchProducts.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(searchProducts.fulfilled, (state, action: PayloadAction<Product[]>) => {
        state.loading = false;
        state.searchResults = action.payload;
        state.error = null;
      })
      .addCase(searchProducts.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string;
      });

    // 获取产品推荐
    builder
      .addCase(fetchRecommendations.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(fetchRecommendations.fulfilled, (state, action: PayloadAction<Product[]>) => {
        state.loading = false;
        state.recommendations = action.payload;
        state.error = null;
      })
      .addCase(fetchRecommendations.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string;
      });
  },
});

export const {
  clearError,
  setFilters,
  clearFilters,
  setPagination,
  clearSearchResults,
  clearRecommendations,
  setCurrentProduct,
} = productSlice.actions;

export default productSlice.reducer;